<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2021/3/4 0004 10:28
 * Describe: 企业微信模型类
 */

namespace app\common\model\corp;

use think\Exception;
use app\common\model\Base;
use app\common\server\corp\{Token, Media};

class Corp extends Base
{
    protected $name = 'wechat_corp';

    /**
     * 添加企业微信
     * @param array $postData
     * @throws Exception
     * @return int
     */
    public function addCorp(array $postData)
    {
        $corpData = $postData;
        unset($corpData['way']);
        $way = $postData['way'];

        $this->startTrans();
        try{
            if($this->where('corpid', $postData['corpid'])->value('id')){
                check_exception('企业corpid已存在');
            }
            $corpData['create_time'] = time();
            $corpData['auth_status'] = 1;
            $corpId = $this->insertGetId($corpData);
            array_map(function(&$value) use($corpId){
                $value['corp_id'] = $corpId;
                $value['create_time'] = time();
            }, $way);

            db('wechat_corp_way')->insertAll($way);

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            exception($e->getMessage());
        }

        return $corpId;
    }

    /**
     * 获取企业欢迎语
     * @link https://work.weixin.qq.com/api/doc/90001/90143/92599
     * @param string $corpId 企业微信corpId 非主键ID
     * @return string
     */
    public function getCorpWelcomeMsgByCorpId(string $corpId): array
    {
        $welcomeMsg = $this->alias('c')
            ->join('w_wechat_corp_way w', 'c.id=w.corp_id', 'LEFT')
            ->where('c.corpid', $corpId)
            ->where('w.type', 1)
            ->value('w.content');
        if(!empty($welcomeMsg)){
            if(strpos($welcomeMsg, 'http') !== false){//链接消息
                $temp['link'] = [
                    'title'  => config('queue.corp')['link']['title']?? '',
                    'picurl' => config('queue.corp')['link']['picurl']?? '',
                    'desc'   => config('queue.corp')['link']['desc']?? '',
                    'url'    => $welcomeMsg
                ];
            }else if($welcomeMsg == 'app'){//小程序消息
                $authCorpAccessToken = (new Token())->getAuthCorpAccessToken($corpId);
                $mediaId = (new Media)->uploadTempMedia($authCorpAccessToken);
                $temp['miniprogram'] = [
                    'title'        => config('queue.corp')['miniprogram']['title']?? '',
                    'pic_media_id' => $mediaId,
                    'appid'        => config('queue.corp')['miniprogram']['appid']?? '',
                    'page'         => config('queue.corp')['miniprogram']['page']?? '',
                ];
            }else{//文本消息
                $temp['text'] = [
                    'content' => $welcomeMsg
                ];
            }
        }
        return $temp?? [];
    }

    /**
     * 编辑企业
     * @param array $postData
     * @throws Exception
     */
    public function editCorp(array $postData): void
    {
        $corpData = $postData;
        unset($corpData['way']);
        $way = $postData['way'];

        $this->startTrans();
        try{
            if($this->where('id', '<>', $postData['id'])->where('corpid', $postData['corpid'])->value('id')){
                check_exception('企业corpid已存在');
            }
            $corpData['update_time'] = time();
            $this->update($corpData);

            db('wechat_corp_way')->where('corp_id', $postData['id'])->delete();

            $corpId = $postData['id'];
            array_map(function($value) use($corpId){
                $value['corp_id'] = $corpId;
                $value['update_time'] = time();
                if(!db('wechat_corp_way')->insert($value)){
                    exception('新增失败');
                }
            }, $way);

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            exception($e->getMessage());
        }
    }

    /**
     * 取消授权
     * @param string $corpId 企业微信的corpId 非主键ID
     */
    public function cancelAuth(string $corpId): void
    {
        $this->where('corpid', $corpId)->update(['auth_status' => 3]);
    }

}